<template>
  <div class="app-container">
    <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules">
      <el-form-item label="学科：" required>
        <el-select v-model="form.subjectId" @change="subjectChange">
          <el-option v-for="item in subjectAll" :key="item.id" :value="item.id" :label="item.categoryName" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="试卷类型：" prop="paperType" required>
        <el-select v-model="form.paperTypeId" placeholder="试卷类型" @change="paperTypeChange">
          <el-option v-for="item in paperTypeEnum" :key="item.id" :value="item.id" :label="item.categoryName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间限制：" required v-show="form.paperTypeId===35">
        <el-date-picker v-model="form.limitDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="试卷年份：" required v-show="form.paperTypeId===33">
        <el-select v-model="form.level" placeholder="请选择年份">
          <el-option v-for="year in years" :key="year" :label="year" :value="year"/>
        </el-select>
<!--        <el-input-number v-model="form.level"></el-input-number>-->
      </el-form-item>
      <el-form-item label="试卷名称："  prop="name" required>
        <el-input v-model="form.name"/>
      </el-form-item>
      <el-form-item>
        <span style="color: red" v-show="biaoti">请至少添加一个标题</span>
      </el-form-item>
      <el-form-item :key="index" :label="'标题'+(index+1)+'：'" required v-for="(titleItem,index) in form.titleItems">
<!--        <el-input v-model="titleItem.name" style="width: 80%" @change="inputClick()"/>-->
          <el-select v-model="titleItem.name">
            <el-option v-for="item in questionType" :key="item[0]" :value="item[1]" :label="item[1]" ></el-option>
          </el-select>
        <el-button type="text" class="link-left" style="margin-left: 20px" size="mini" @click="addQuestion(titleItem)">
          添加题目
        </el-button>
        <el-button type="text" class="link-left" size="mini" @click="form.titleItems.splice(index,1)">删除</el-button>
        <el-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
          <el-form-item :key="questionIndex" :label="'题目'+(questionIndex+1)+'：'"
                        v-for="(questionItem,questionIndex) in titleItem.questionItems" style="margin-bottom: 15px">
            <el-row>
              <el-col :span="23">
                <QuestionShow :qType="questionItem.questionType" :question="questionItem"/>
              </el-col>
              <el-col :span="1">
                <el-button type="text" size="mini" @click="titleItem.questionItems.splice(questionIndex,1)">删除
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-card>
      </el-form-item>
      <el-form-item>
        <span style="color: red" v-show="biaotinr">{{btnr}}</span>
        <span style="color: red" v-show="timusl">{{tmnr}}</span>
      </el-form-item>
      <el-form-item label="建议时长：" prop="suggestTime">
        <el-input v-model="form.suggestTime" placeholder="分钟"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="success" @click="addTitle">添加标题</el-button>
      </el-form-item>
    </el-form>
  <!--添加试题部分-->
    <el-dialog :visible.sync="questionPage.showDialog"  width="70%">
      <el-form :model="questionPage.queryParam" ref="queryForm" :inline="true">
<!--        <el-form-item label="题目ID：">
          <el-input v-model="questionPage.queryParam.id" clearable></el-input>
        </el-form-item>-->
        <el-form-item label="题目内容：">
          <el-input v-model="questionPage.queryParam.content" clearable></el-input>
        </el-form-item>
        <el-form-item label="大学科：">
          <el-select v-model="questionPage.queryParam.subjectParentId" placeholder="学科" @change="mainSubjectChange01" clearable>
            <el-option v-for="item in mainSubject" :key="item[0]" :value="item[0]" :label="item[1]"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小学科：">
          <el-select v-model="questionPage.queryParam.subjectId" placeholder="小学科" @change="mainSubjectChange02"  clearable>
            <!-- 内层循环遍历对应主学科下的小学科列表，这里使用template标签包裹来进行正确的循环逻辑 -->
            <template v-for="mainItem in mainSubject01">
              <el-option v-for="subItem in mainItem[2]" :key="subItem[0]" :value="subItem[0]" :label="subItem[1]">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：">
          <el-select v-model="questionPage.queryParam.questionType" placeholder="题型"  clearable>
            <el-option v-for="item in allQuestionType" :key="item[0]" :value="item[0]" :label="item[1]"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年份">
          <el-input-number v-model="questionPage.queryParam.gradeLevel"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryForm">查询</el-button>
        </el-form-item>
      </el-form>
      <!--题目-->
      <el-table v-loading="questionPage.listLoading" :data="questionPage.tableData"
                @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
        <el-table-column type="selection" width="35"></el-table-column>
        <el-table-column prop="id" label="Id" width="90px"/>
        <el-table-column prop="subjectName" label="学科"  width="120px"/>
        <el-table-column prop="questionTypeName" label="题型" width="70px"/>
        <el-table-column prop="gradeLevel" label="年份" width="70px"/>
        <el-table-column prop="articleContent" label="材料" show-overflow-tooltip/>
        <el-table-column prop="textContent" label="题干"  show-overflow-tooltip/>
        <el-table-column prop="score" label="分数" width="60px"/>
        <el-table-column prop="createTime" label="创建时间" width="160px"/>
<!--        <el-table-column prop="id" label="Id" width="60px"/>
        <el-table-column prop="questionType" label="题型" :formatter="questionTypeFormatter" width="70px"/>
        <el-table-column prop="shortTitle" label="题干" show-overflow-tooltip/>-->
      </el-table>
      <pagination v-show="questionPage.total>0" :total="questionPage.total"
                  :page.sync="questionPage.queryParam.pageIndex" :limit.sync="questionPage.queryParam.pageSize"
                  @pagination="search"/>
      <span slot="footer" class="dialog-footer">
          <el-button @click="questionPage.showDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmQuestionSelect">确定</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters, mapState, mapActions } from 'vuex'
import Pagination from '@/components/Pagination'
import QuestionShow from '../question/components/ShowPaper.vue'
import examPaperApi from '@/api/examPaper'
import questionApi from '@/api/question'

export default {
  components: { Pagination, QuestionShow },
  data () {
    return {
      btnr: null,
      tmnr: null,
      biaoti: false,
      biaotinr: false,
      timusl: false,
      paperTypeEnum: [],
      QuestionType: [],
      allQuestionType: [],
      mainSubject: [],
      allQuestionType01: [],
      mainSubject01: [],
      form: {
        paperId: null,
        subjectId: 1,
        paperType: 33,
        paperTypeId: 33,
        level: null,
        name: '',
        suggestTime: null,
        // limitDateTime: [],
        limitDateTime: [],
        titleItems: []
      },
      years: [],
      questionType: [],
      newquestionType: [],
      subjectFilter: null,
      formLoading: false,
      subjectAll: [],
      rules: {
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        paperType: [
          { required: true, message: '请选择试卷类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入试卷名称', trigger: 'blur' }
        ],
        suggestTime: [
          // { type: 'string', message: '建议时长必须是数字或为空', trigger: 'blur' },
          { validator: this.validataSuggesTime, trigger: 'blur' }
        ],
        limitDateTime: [
          { required: true, message: '请选择考试时间', trigger: 'change' }
        ]
      },
      questionPage: {
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          id: null,
          content: null,
          subjectParentId: null,
          subjectId: null,
          questionType: null,
          gradeLevel: null,
          pageIndex: 1,
          pageSize: 5,
          alerdyItems: []
        },
        listLoading: true,
        tableData: [],
        total: 0
      },
      currentTitleItem: null
    }
  },
  created () {
    this.subjectChange()
    this.generateYears()
    this.paperTypesearch()
    this.typeChange()
    this.subjectAllsearch()
    let id = this.$route.query.id
    let _this = this
    this.initSubject(function () {
      _this.subjectFilter = _this.subjects
    })
    if (id && parseInt(id) !== 0) {
      _this.formLoading = true
      examPaperApi.select(id).then(re => {
        _this.form = re.response
        _this.formLoading = false
      })
    }
  },
  methods: {
    subjectChange () {
      this.questionType = this.newquestionType
      examPaperApi.selectParentId(this.form.subjectId).then(re => {
        // console.log('最终结果：' + re.response)
        this.questionType = this.questionType.filter(data => data[2] === re.response)
      })
    },
    generateYears () {
      const currentYear = new Date().getFullYear()
      for (let i = 0; i < 20; i++) {
        this.years.push(currentYear - i)
      }
    },
    paperTypeChange () {
      if (this.form.paperTypeId === 35) {
        const today = new Date()
        today.setHours(0, 0, 0, 0)
        const sevenDaysLater = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
        sevenDaysLater.setHours(0, 0, 0, 0)

        const formatDate = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        }
        this.form.limitDateTime = [formatDate(today), formatDate(sevenDaysLater)]
      }
      if (this.form.paperTypeId !== 33) {
        this.form.level = null
      }
    },
    inputClick () {
      this.validateTitleItems(this.form.titleItems)
    },
    /** 提交时触发表单验证事件**/
    validateTitleItems (value) {
      console.log('validateTitleItems 被调用了')
      if (value.length === 0) {
        this.biaoti = true
        setTimeout(() => {
          this.biaoti = false
        }, 2000)
        return false
      } else {
        this.biaoti = false
      }
      if (this.form.paperTypeId === 35) {
        console.log(this.form.limitDateTime)
        if (this.form.limitDateTime === null) {
          this.biaotinr = true
          this.btnr = '考试时间不能为空'
          // 延迟2秒后隐藏提示信息
          setTimeout(() => {
            this.biaotinr = false
            this.btnr = ''
          }, 2000)
          return false
        }
      }
      for (let i = 0; i < value.length; i++) {
        const titleItem = value[i]
        if (!titleItem.name || titleItem.name.trim() === '') {
          // callback(new Error(`标题${i + 1}不能为空`))
          this.biaotinr = true
          this.btnr = `标题${i + 1}不能为空`
          setTimeout(() => {
            this.biaotinr = false
            this.btnr = ''
          }, 2000)
          return false
        } else {
          this.biaotinr = false
        }
        if (titleItem.questionItems.length === 0) {
          // callback(new Error(`标题${i + 1}下没有添加题目`))
          this.timusl = true
          this.tmnr = `标题${i + 1}下没有添加题目`
          setTimeout(() => {
            this.timusl = false
            this.tmnr = ''
          }, 2000)
          return false
        } else {
          this.timusl = false
        }
      }
      return true
    },
    validataSuggesTime (rule, value, callback) {
      if (value === null || value === '') {
        callback()
        console.log('建议时长：' + value)
      } else if (value <= 0) {
        callback(new Error('建议时长必须大于0或为空'))
      } else {
        callback()
      }
    },
    paperTypesearch () {
      examPaperApi.paperType().then(data => {
        const re = data.response
        this.paperTypeEnum = re
      })
    },
    typeChange () {
      this.listLoading = true
      questionApi.selectType().then(data => {
        if (data.code === 1) {
          const re = data.response[0]
          this.mainSubject = re.mainSubject
          console.log(this.mainSubject)
          this.allQuestionType = re.allQuestionType
          this.questionType = re.allQuestionType
          this.newquestionType = re.allQuestionType
          this.allQuestionType01 = re.allQuestionType
          this.mainSubject01 = re.mainSubject
          console.log(this.form.subjectId)
          this.questionType = this.questionType.filter(data => data[2] === this.form.subjectId)
          console.log(this.questionType)
        } else {
          console.error('获取数据失败，原因：', data.message)
        }
        this.listLoading = false
      }
      )
    },
    mainSubjectChange01 () {
      // 这里编写当主科目选项改变时需要执行的逻辑，例如加载对应主科目的相关题型等
      // console.log('主科目选项发生改变，当前选中的值为：', this.questionPage.queryParam.subjectParentId)
      this.allQuestionType = this.allQuestionType01
      this.allQuestionType = this.allQuestionType.filter(data => data[2] === this.questionPage.queryParam.subjectParentId)
      this.mainSubject01 = this.mainSubject.filter(data => data[0] === this.questionPage.queryParam.subjectParentId)
    },
    mainSubjectChange02 () {

    },
    subjectAllsearch () {
      examPaperApi.subjectList().then(data => {
        const re = data.response
        this.subjectAll = re
        // console.log(re)
      })
    },
    submitFormSelect () {
      this.search() // 欠缺修改
    },
    submitForm () {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.validateTitleItems(this.form.titleItems)) {
            return false
          }
          this.formLoading = true
          console.log('提交试卷内容')
          console.log(this.form)
          this.form.paperType = this.form.paperTypeId
          examPaperApi.edit(this.form).then(re => {
            if (re.code === 1) {
              _this.$message.success(re.message)
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/exam/paper/list')
              })
            } else {
              _this.$message.error(re.message)
              this.formLoading = false
            }
          }).catch(e => {
            this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    addTitle () {
      this.biaoti = false
      this.form.titleItems.push({
        name: '',
        questionItems: []
      })
    },
    addQuestion (titleItem) {
      /** 点击添加题目后触发的事件**/
      this.timusl = false
      // console.log('已有题目列表')
      this.questionPage.queryParam.alerdyItems = this.form.titleItems
      // console.log(this.questionPage.queryParam.alerdyItems)
      this.currentTitleItem = titleItem
      this.questionPage.showDialog = true
      this.search()
    },
    removeTitleItem (titleItem) {
      this.form.titleItems.remove(titleItem)
    },
    removeQuestion (titleItem, questionItem) {
      titleItem.questionItems.remove(questionItem)
    },
    queryForm () {
      this.questionPage.queryParam.pageIndex = 1
      this.search()
    },
    confirmQuestionSelect () {
      let _this = this
      this.questionPage.multipleSelection.forEach(q => {
        questionApi.selectTm(q.id).then(re => {
          _this.currentTitleItem.questionItems.push(re.response)
          console.log('添加题目')
          console.log(re.response)
        })
      })
      this.questionPage.showDialog = false
    },
    search () {
      this.questionPage.listLoading = true
      console.log('查询参数')
      console.log(this.questionPage.queryParam)
      questionApi.pageOtherList(this.questionPage.queryParam).then(data => {
        const re = data.response
        console.log(re.list)
        this.questionPage.tableData = re.list
        console.log('内容：' + this.questionPage.tableData)
        console.log(this.questionPage.tableData)
        this.questionPage.total = re.total
        this.questionPage.queryParam.pageIndex = re.pageNum
        this.questionPage.listLoading = false
      })
    },
    handleSelectionChange (val) {
      this.questionPage.multipleSelection = val
    },
    questionTypeFormatter (row, column, cellValue, index) {
      return this.enumFormat(this.questionTypeEnum, cellValue)
    },
    subjectFormatter (row, column, cellValue, index) {
      return this.subjectEnumFormat(cellValue)
    },
    resetForm () {
      let lastId = this.form.paperId
      if (lastId != null) {
        examPaperApi.select(lastId).then(re => {
          this.form = re.response
        })
      } else {
        this.$refs['form'].resetFields()
        this.form = {
          id: null,
          subjectId: null,
          paperType: 33,
          limitDateTime: [],
          name: '',
          suggestTime: null,
          titleItems: []
        }
      }
      this.form.id = lastId
    },
    ...mapActions('exam', { initSubject: 'initSubject' }),
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {
    ...mapGetters('enumItem', ['enumFormat']),
    ...mapState('enumItem', {
      questionTypeEnum: state => state.exam.question.typeEnum
      // paperTypeEnum: state => state.exam.examPaper.paperTypeEnum
    }),
    ...mapState('exam', { subjects: state => state.subjects })
  }
}
</script>

<style lang="scss">
   .tishi {
     background-color: lightskyblue;
     color: red;
     width: 400px;
     height: 45px;
     text-align: left;
     line-height: 45px;
     display: inline-block;
     font-size: 20px;
     padding-left: 10px;
  }
  .exampaper-item-box {
    .q-title {
      margin: 0px 5px 0px 5px;
    }
    .q-item-content {
    }
  }
</style>
